/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useRef, useState } from "react";
import { io, Socket } from "socket.io-client";
import styles from "./css/chat.module.less";
import { Button, message, Popover } from "antd";
import { chatHistoryList, chatroomList } from "../../interfaces";
import TextArea from "antd/es/input/TextArea";
import { useLocation } from "react-router-dom";
import EmojiPicker from "@emoji-mart/react";
import data from "@emoji-mart/data";
import { UploadImageModal } from "./uploadingImageModal";

interface JoinRoomPayload {
  chatroomId: number;
  userId: number;
}

interface SendMessagePayload {
  sendUserId: number;
  chatroomId: number;
  message: Message;
}

interface Message {
  type: MessageType
  content: string
}

type MessageType = 'image' | 'text' | 'file';


type Reply =
  | {
      type: "sendMessage";
      userId: number;
      message: ChatHistory;
    }
  | {
      type: "joinRoom";
      userId: number;
    };

interface Chatroom {
  id: number;
  name: string;
  createTime: Date;
}

interface ChatHistory {
  id: number;
  content: string;
  type: number;
  chatroomId: number;
  senderId: number;
  createTime: Date;
  sender: UserInfo;
}

interface User {
  id: number;
  email: string;
  headPic: string;
  nickName: string;
  username: string;
  createTime: Date;
}






export function getUserInfo(): User {
  return JSON.parse(localStorage.getItem("userInfo")!);
}

export default function Chat() {
  const socketRef = useRef<Socket>();
  const [roomId, setChatroomId] = useState<number>();
  const useInfo = getUserInfo();
  const [isUploadImageModalOpen,setUploadImageModalOpen] = useState(false);

  useEffect(() => {
    if (!roomId) {
      return;
    }
    const socket = (socketRef.current = io("http://localhost:3005"));
    socket.on("connect", function () {
      const payload: JoinRoomPayload = {
        chatroomId: roomId,
        userId: getUserInfo().id,
      };

      socket.emit("joinRoom", payload);

      socket.on("message", (reply: Reply) => {
        if (reply.type === "sendMessage") {
          setChatHistory((chatHistory) => {
            return chatHistory
              ? [...chatHistory, reply.message]
              : [reply.message];
          });
          setTimeout(() => {
            //发送消息后自动滚到底
            document
              .getElementById("bottom-bar")
              ?.scrollIntoView({ block: "end" });
          }, 300);
        }
      });
    });
    return () => {
      socket.disconnect();
    };
  }, [roomId]);

  async function addToFavorite(chatHistoryId: number) {
    try{
        const res = await favoriteAdd(chatHistoryId);

        if(res.status === 201 || res.status === 200) {
            message.success('收藏成功')
        }
    } catch(e: any){
        message.error(e.response?.data?.message || '系统繁忙，请稍后再试');
    }
}

  function sendMessage(value?: string,type:MessageType = 'text') {
    if (!value) {
      return;
    }
    if (!roomId) {
      return;
    }

    const payload: SendMessagePayload = {
      sendUserId: getUserInfo().id,
      chatroomId: roomId,
      message: {
        type,
        content: value,
      },
    };

    socketRef.current?.emit("sendMessage", payload);
  }

  const [rommList, setRoomList] = useState<Array<Chatroom>>();
  async function queryChatroomList() {
    try {
      const res = await chatroomList();

      if (res.status === 201 || res.status === 200) {
        setRoomList(
          res.data.map((item: Chatroom) => {
            return {
              ...item,
              key: item.id,
            };
          })
        );
      }
    } catch (e: any) {
      message.error(e.response?.data?.message || "系统繁忙，请稍后再试");
    }
  }
  useEffect(() => {
    queryChatroomList();
  }, []);

  useEffect(() => {
    setTimeout(() => {
      document.getElementById("bottom_bar")?.scrollIntoView({ block: "end" });
    }, 300);
  }, [roomId]);

  //点击聊天室的时候查询对应聊天记录
  const [chatHistory, setChatHistory] = useState<Array<ChatHistory>>();
  async function queryChatHistoryList(chatroomId: number) {
    try {
      const res = await chatHistoryList(chatroomId);

      if (res.status === 201 || res.status === 200) {
        setChatHistory(
          res.data.map((item: Chatroom) => {
            return {
              ...item,
              key: item.id,
            };
          })
        );
      }
    } catch (e: any) {
      message.error(e.response?.data?.message || "系统繁忙，请稍后再试");
    }
  }

  //发送消息功能
  const [inputText, setInputText] = useState("");

  const location = useLocation();

  useEffect(() => {
    if (location.state?.chatroomId) {
      setChatroomId(location.state?.chatroomId);
      queryChatHistoryList(location.state?.chatroomId);
    }
  }, [location.state?.chatroomId]);

  return (
    <div id={styles.chat_container}>
      <div className={styles.chat_list_container}>
        <div className={styles.chat_list}>
          {rommList?.map((item) => {
            const isSelected = item.id === roomId;
            return (
              <div
                className={`${styles.chat_list_item} ${
                  isSelected ? styles["selected"] : ""
                }`}
                data-id={item.id}
                onClick={() => {
                  queryChatHistoryList(item.id);
                  setChatroomId(item.id);
                }}
              >
                {item.name}
              </div>
            );
          })}
        </div>
      </div>
      <div className={styles.message_list}>
        {chatHistory?.map((item) => {
          //如果是自己发送的消息，则显示在右边，否则显示在左边
          const isFromMe = item.senderId === useInfo.id;
          return (
            <div
              className={`${styles.message_item} ${
                isFromMe ? styles["from_me"] : ""
              }`}
              data-id={item.id}
              key={item.id}
              onDoubleClick={() =>{
                addToFavorite(item.id)
              }}
            >
              <div className={styles.message_sender}>
                <img src={item.sender.headPic} />
                <span className={styles.message_nickname}>
                  {item.sender.nickName}
                </span>
              </div>
              <div className={styles.message_content}>{item.content}</div>
            </div>
          );
        })}
        <div id="bottom_bar" key="bottom_bar"></div>
      </div>
      <div className={styles.message_input}>
        <div className={styles.message_type}>
          <div className={styles.message_type_item} key={1}>
            <Popover
              content={
                <EmojiPicker
                  data={data}
                  onEmojiSelect={(emoji: any) => {
                    setInputText((inputText) => inputText + emoji.native);
                  }}
                />
              }
              title="Title"
              trigger="click"
            >
              表情
            </Popover>
          </div>
          <div className={styles.message_type_item } key={2} onClick={() =>{
            setUploadImageModalOpen(true);
          }}>图片</div>
          <div className={styles.message_type_item} key={3}>文件</div>
          {/* TODO */}
        </div>
        <div className={styles.message_input_area}>
          <TextArea
            className={styles.message_input_box}
            value={inputText}
            onChange={(e) => {
              setInputText(e.target.value);
            }}
          />
          <Button
            className={styles.message_send_btn}
            type="primary"
            onClick={() => {
              sendMessage(inputText);
              setInputText("");
            }}
          >
            发送
          </Button>
        </div>
      </div>
      <UploadImageModal
      isOpen={isUploadImageModalOpen}
      handleClose={(imgSrc) =>{
        setUploadImageModalOpen(false);
        if(!imgSrc){
          sendMessage(imgSrc, 'image')
        }
      }}
      />

    </div>
  );
}
